import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/index/iview/banner_iview.dart';
import 'package:flutter_deer/index/iview/football_ratio_iview.dart';
import 'package:flutter_deer/index/models/banner_entity.dart';
import 'package:flutter_deer/index/models/football_ratio_entity.dart';
import 'package:flutter_deer/index/page/game_unstart_list_page.dart';
import 'package:flutter_deer/index/presenter/banner_presenter.dart';
import 'package:flutter_deer/index/provider/index_page_provider.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/my_card.dart';
import 'package:flutter_deer/widgets/neon_container.dart';
import 'package:provider/provider.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';
import 'package:flutter_deer/widgets/fadein_text.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import '../index_router.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({super.key});

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage>
    with
        AutomaticKeepAliveClientMixin<IndexPage>,
        SingleTickerProviderStateMixin,
        BasePageMixin<IndexPage, PowerPresenter>
    implements BannerIMvpView, FootballRatioIMvpView {
  @override
  bool get wantKeepAlive => false;
  IndexPageProvider provider = IndexPageProvider();
  late BannerPagePresenter bannerPagePresenter;

  List<String> _menuTitle = [];
  final List<String> _menuImage = [
    'zbdj',
    'xmzjdb',
    'zcjd',
    'dwzbmx',
    'lszf',
    'yszxjdfx',
    'gkxjjc',
    'czsrfx'
  ];
  final List<String> _menuDarkImage = [
    'zbdj_dark',
    'xmzjdb_dark',
    'zcjd_dark',
    'dwzbmx_dark',
    'lszf_dark',
    'yszxjdfx_dark',
    'gkxjjc_dark',
    'czsrfx_dark'
  ];

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter =
        PowerPresenter<dynamic>(this);
    bannerPagePresenter = new BannerPagePresenter();
    powerPresenter.requestPresenter([bannerPagePresenter]);
    return powerPresenter;
  }

  @override
  void setBanners(List<BannerEntity>? banners) {
    provider.setBannerList(banners);
  }

  // @override
  // void setFootballRatioGroupList(List<FootballRatioGroupEntity>? groupList) {
  //   provider.setFootballRatioGroupList(groupList);
  // }

  // TabController? _tabController;
  // List<GameUnstartListPage> listPages = [];

  @override
  void initState() {
    super.initState();
    if (mounted) {
      Future.delayed(
          Duration(seconds: 1), () => {bannerPagePresenter.getBannerList()});
    }
    // _tabController = TabController(vsync: this, length: 2);
    // listPages = [GameUnstartListPage(index:0),GameUnstartListPage(index:1)];
  }

  @override
  void dispose() {
    // provider.dispose();
    // _tabController?.dispose();
    super.dispose();
  }

  @override
  // ignore: must_call_super
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  bool isDark = true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    isDark = context.isDark;
    _menuTitle = [
      '${DeerLocalizations.of(context)!.navIndicatorDocument.nullSafe}',
      '${DeerLocalizations.of(context)!.navComparisonFunds.nullSafe}',
      '${DeerLocalizations.of(context)!.navExpenditureProgress.nullSafe}',
      '${DeerLocalizations.of(context)!.navUnitIndicatorDetails.nullSafe}',
      '${DeerLocalizations.of(context)!.navHistoricalPayment.nullSafe}',
      '${DeerLocalizations.of(context)!.navAnalysisBudgetExecutionProgress.nullSafe}',
      '${DeerLocalizations.of(context)!.navTreasuryCashMonitoring.nullSafe}',
      '${DeerLocalizations.of(context)!.navAnalysisOfFiscalRevenue.nullSafe}'
    ];
    final Widget line = Container(
      height: 6,
      width: MediaQuery.of(context).size.width,
      margin: const EdgeInsets.only(left: 0.0, right: 0.0),
      color:
          context.isDark ? Colors.transparent : Colours.unselected_item_color,
      child: context.isDark
          ? Gaps.line
          : Visibility(
              visible: false,
              child: Row(),
            ),
    );
    return ChangeNotifierProvider<IndexPageProvider>(
        create: (_) => provider,
        child: Scaffold(
          appBar: PreferredSize(
            preferredSize: Size.fromHeight(200),
            child: Container(
              width: MediaQuery.of(context).size.width,
              child: Consumer<IndexPageProvider>(builder: (_, provider, child) {
                return MyCard(
                    child: Container(
                        height: 200.0,
                        padding: EdgeInsets.only(top: 0.0),
                        child: provider.bannerLoading == true
                            ? LoadingAnimationWidget.dotsTriangle(
                                color: isDark
                                    ? Colors.white
                                    : Colours.dark_app_main,
                                size: 50,
                              )
                            : Swiper(
                                autoplay: true,
                                itemBuilder: (context, index) {
                                  BannerEntity? banner =
                                      provider.bannerList!.elementAt(index);
                                  return GestureDetector(
                                      onTap: () {
                                        NavigatorUtils.push(context,
                                            IndexRouter.bannerDetailPage,
                                            arguments: banner.id.toString());
                                      },
                                      child: Container(
                                        width:
                                            MediaQuery.of(context).size.width,
                                        child: Image(
                                          image: ImageUtils.getImageProvider(
                                              Constant.imageServerHost +
                                                  '${banner.image}',
                                              holderImg: 'shop/tx'),
                                          width:
                                              MediaQuery.of(context).size.width,
                                          fit: BoxFit.fitHeight,
                                        ),
                                      ));
                                },
                                itemCount: provider!.bannerList!.length)));
              }),
            ),
          ),
          body: Consumer<IndexPageProvider>(builder: (_, provider, child) {
            return SingleChildScrollView(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                    padding: EdgeInsets.only(left: 0.0, right: 0.0),
                    color: context.backgroundColor,
                    child: _NavFunctionModule(
                        data: _menuTitle,
                        image: _menuImage,
                        darkImage: _menuDarkImage,
                        onItemClick: (index) {
                          switch (index) {
                            case 0:
                              NavigatorUtils.push(context, IndexRouter.indicatorDocumentListPage);
                              break;
                            case 1:
                              NavigatorUtils.push(context, IndexRouter.capitalComparison);
                              break;
                            case 2:
                              NavigatorUtils.push(context, IndexRouter.expenditureProgress);
                              break;
                            case 4:
                              NavigatorUtils.push(context, IndexRouter.historicalExpenditure);
                              break;
                            // 如果需要处理其他index值，可以在这里添加case
                            default:
                              // 这里可以处理未定义的index值，比如打印日志或者执行某个默认操作
                              // print('Unknown index: $index');
                              break;
                          }

                        })),
                Visibility(
                  visible: context.isDark,
                  child: Gaps.vGap24,
                ),
                line,
                Gaps.vGap24,
                MergeSemantics(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16.0),
                    child: Text(
                      '${DeerLocalizations.of(context)!.dataStatistics.nullSafe}',
                      style: TextStyles.textBold18,
                    ),
                  ),
                ),
                Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        NeonContainer(
                          text: '执行进度',
                          color: Colors.white24,
                          borderColor: isDark
                              ? Colors.white30
                              : Theme.of(context).primaryColor,
                          icon: "icon_zxjd",
                          darkIcon: "icon_zxjd_dark",
                          animateAfterChanges: true,
                          onTap: () => NavigatorUtils.push(context, IndexRouter.executionProgressPage),

                        ),
                        NeonContainer(
                          text: '执行分析',
                          color: Colors.white24,
                          borderColor: isDark
                              ? Colors.white30
                              : Theme.of(context).primaryColor,
                          icon: "icon_zxfx",
                          darkIcon: "icon_zxfx_dark",
                          onTap: () {
                            print('blue pressed');
                          },
                        ),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        NeonContainer(
                          text: '支出占比',
                          color: Colors.white24,
                          icon: "icon_zczb",
                          darkIcon: "icon_zczb_dark",
                          onTap: () {
                            print('blue pressed');
                          },
                        ),
                        NeonContainer(
                          text: '代码集',
                          color: Colors.white24,
                          icon: "icon_sjzd",
                          darkIcon: "icon_sjzd_dark",
                          onTap: () {
                            print('blue pressed');
                          },
                        ),
                      ],
                    )
                  ],
                )
              ],
            ));
          }),
        ));
  }

  // PageController _pageController = PageController();
  // Future<void> _onPageChange(int index) async {
  //   provider.setIndex(index);
  //   _tabController?.animateTo(index, duration: Duration.zero);
  //   _pageController.jumpToPage(index);
  // }
}

class _NavFunctionModule extends StatelessWidget {
  const _NavFunctionModule({
    required this.onItemClick,
    required this.data,
    required this.image,
    required this.darkImage,
  });

  final Function(int index) onItemClick;
  final List<String> data;
  final List<String> image;
  final List<String> darkImage;

  @override
  Widget build(BuildContext context) {
    double textWidth = 0;
    for (int i = 0; i < data.length; i++) {
      TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: data.elementAt(i),
        ),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      if (textWidth < textPainter.size.width) {
        textWidth = textPainter.size.width;
      }
    }
    int crossAxisCount = 4;
    if (textWidth > MediaQuery.of(context).size.width / 4 - 40) {
      crossAxisCount = 3;
    }
    return AnimationLimiter(
        child: GridView.builder(
      shrinkWrap: true,
      padding: EdgeInsets.fromLTRB(8.0, 0, 8.0, 12.0),
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        childAspectRatio: 1.18,
      ),
      itemCount: data.length,
      itemBuilder: (_, index) {
        return AnimationConfiguration.staggeredGrid(
          position: index,
          duration: Duration(milliseconds: 500),
          columnCount: 4,
          child: ScaleAnimation(
            child: FadeInAnimation(
                child: InkWell(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  LoadAssetImage(
                      context.isDark
                          ? 'home/${darkImage[index]}'
                          : 'home/${image[index]}',
                      width: 32.0),
                  Gaps.vGap4,
                  FadeInText(
                    text: data[index],
                    // style: TextStyles.textSize12,
                  )
                ],
              ),
              onTap: () {
                onItemClick(index);
              },
            )),
          ),
        );
      },
    ));
  }
}
